package com.greatwqs.wmall.gateway.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;

import lombok.extern.slf4j.Slf4j;

/**
 * Nacos 注册优雅下线 (监听 ContextClosedEvent)
 * <a href="https://gitee.com/greatwqs/wmall-be/issues/ICCYD2">Kubernates RollingUpdate 滚动更新</a>
 *
 * @author wang-qingsong
 * @since 2025-06-05
 */
@Slf4j
@Component
public class NacosDeregisterHook implements ApplicationListener<ContextClosedEvent> {

    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        // 手动触发Nacos服务注销
        nacosAutoServiceRegistration.destroy();
        log.warn("NacosDeregisterHook nacosAutoServiceRegistration destroy called!");

        // 可选：添加等待逻辑，确保正在处理的请求完成
        try {
            Thread.sleep(2000);
        }
        catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}